package com.skt.controller;

import com.skt.domain.DTO.request.CreateRentalOrderRequest;
import com.skt.domain.VO.RentalOrderVO;
import com.skt.security.LoginUser;
import com.skt.service.RentalOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/orders")
@RequiredArgsConstructor
@Tag(name = "订单接口")
public class RentalOrderController {

    private final RentalOrderService rentalOrderService;

    @Operation(summary = "创建租赁订单")
    @PostMapping
    public RentalOrderVO createRentalOrder(@Valid @RequestBody CreateRentalOrderRequest request) {
        return rentalOrderService.createRentalOrder(request);
    }

    @Operation(summary = "查询订单详情")
    @GetMapping("/{id}")
    public RentalOrderVO getOrderDetail(@PathVariable Long id) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !(auth.getPrincipal() instanceof LoginUser)) {
            throw new RuntimeException("用户未登录");
        }
        Long currentUserId = ((LoginUser) auth.getPrincipal()).getUserId();
        return rentalOrderService.getOrderDetail(id, currentUserId);
    }

    @Operation(summary = "查询我的订单列表")
    @GetMapping
    public List<RentalOrderVO> listMyOrders(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return rentalOrderService.listMyOrders(pageNum, pageSize);
    }

    @Operation(summary = "取消未生效的订单")
    @PostMapping("/{id}/cancel")
    public ResponseEntity<RentalOrderVO> cancelPendingOrder(@PathVariable Long id) {
        RentalOrderVO canceledOrder = rentalOrderService.cancelPendingOrder(id);
        // 表示返回一个状态码为 200 OK、响应体为 canceledOrder 对象的 HTTP 响应。代码
        return ResponseEntity.ok(canceledOrder);
    }
}
